﻿using Microsoft.Extensions.DependencyInjection;

using MQTTnet;
using MQTTnet.Exceptions;
using MQTTnet.Formatter;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Admin.NET.Plugin.MQTT.MQTT
{
    public static class MqttClientSetup
    {
        public static IMqttClient? mqttClient = null;
        public static MqttClientOptions? mqttClientOptions = null;
        public static void AddMqttClient(this IServiceCollection services)
        {
            try
            {
                if (mqttClient == null)
                {

                    mqttClient = new MqttClientFactory().CreateMqttClient();
                   
                    mqttClientOptions = new MqttClientOptionsBuilder()
                       .WithTcpServer($"127.0.0.1", 10025)
                       .WithCredentials("admin", "123456")
                       .WithClientId("testclient-001")
                       .WithCleanSession(true)
                       .WithProtocolVersion(MqttProtocolVersion.V500)
                       .WithKeepAlivePeriod(TimeSpan.FromSeconds(30)) // 设置心跳包间隔为30秒
                       .Build();
                    services.AddSingleton<MqttClientOptions>(mqttClientOptions);
                    services.AddSingleton<IMqttClient>(mqttClient);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"MQTT服务启动失败，{ex.Message}");
            }

        }
        //private static Task MqttClient_ApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs arg)
        //{
        //    return Task.CompletedTask;
        //}

        //private static Task MqttClient_DisconnectedAsync(MqttClientDisconnectedEventArgs arg)
        //{
        //    Console.WriteLine("客户端连接失败");
        //    try
        //    {
        //        mqttClient.ReconnectAsync();
        //    }
        //    catch (MqttCommunicationException ex)
        //    {
        //        Task.Delay(2000);
        //    }
        //    return Task.CompletedTask;
        //}

        //private static Task MqttClient_ConnectedAsync(MqttClientConnectedEventArgs arg)
        //{
        //    Console.WriteLine("客户端连接成功");
        //    return Task.CompletedTask;
        //}

    }
}
